class TW {
  constructor() {
    this.queue = []; 
    this.index = 0;   
	this.dom;
    this.cursor = "_";
    this.init();
  }

  // 因为执行需要在函数收集之前，因此需要利用事件机制，先收集后执行
  init() {
    setTimeout(() => this.run() , 0);
  }
  // 见名字和结合代码就知道作用
  run() {
    const fn = this.queue[this.index++];
    fn && fn();
  }
  
  sleep (s = 1000){
    // 将程序暂缓一段时间 默认为 1s
  	this.queue.push(() => {
      setTimeout(() => {
        this.run();
      },s);
    });
    return this;
  }

  twsetup (dom,cursor = "_"){
    /* 目前两个参数
	*  @dom ：应为string类型 元素的id，如果绑定不到则退出整个方法
	*  @cursor : 应为string类型 输出时的光标样式，默认为_ 
	*/
    this.queue.push(() => {
      this.cursor = cursor;
      if(null == document.getElementById(dom)){
	    console.log("No related element was found.");
      }else{
        this.dom = document.getElementById(dom);
        this.dom.innerHTML += this.cursor;
        this.run();
      }
    });
    return this;
  } 

  clear (s = 100){
	// 删除，模拟打字退格
	this.queue.push(() => {
      let timer = setInterval(() => {
        this.dom.innerHTML = this.dom.innerHTML.slice(0,this.dom.innerHTML.length-1);
        if(this.dom.innerHTML == ""){
            clearInterval(timer);
            this.run();
        }
      },s);
    });
    return this;
  }

  clearAll () {
    this.queue.push(() => {
      // 将元素内容清空
      this.dom.innerHTML = "";
      this.run();
    });
	return this;
  }

  tw (str,s=150){
    // 输出
    this.queue.push(() =>{
      var i = 0;
      var e = setInterval(()=>{
        //this.dom.innerHTML += str.charAt(i);
        this.dom.innerHTML = str.slice(0, i) + this.cursor;
        if(i < str.length){
          i++;
        }else{
          this.dom.innerHTML = this.dom.innerHTML.slice(0,this.dom.innerHTML.length-1);
          clearInterval(e);
          this.run();
        }
      },s);
    });
    return this;
  }
};